package com.github.itdachen.auth.oauth.rbac.storage.permission;

import com.alibaba.fastjson2.JSON;
import com.github.itdachen.auth.oauth.rbac.constants.RedisKeyConstant;
import com.github.itdachen.auth.oauth.rbac.handler.IUserPermissionHandler;
import com.github.itdachen.auth.oauth.rbac.storage.IUserPermissionStorageHandler;
import com.github.itdachen.framework.context.constants.UserTypeConstant;
import com.github.itdachen.framework.context.permission.PermissionInfo;
import com.github.itdachen.framework.context.userdetails.UserInfoDetails;
import com.github.itdachen.framework.core.utils.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 用户权限
 *
 * @author 王大宸
 * @date 2025-02-18 15:49
 */
@Service
public class RbacUserPermissionStorageStorageStrategy implements IUserPermissionStorageHandler {
    private final IUserPermissionHandler userPermissionHandler;
    private final StringRedisTemplate stringRedisTemplate;

    public RbacUserPermissionStorageStorageStrategy(IUserPermissionHandler userPermissionHandler,
                                                    StringRedisTemplate stringRedisTemplate) {
        this.userPermissionHandler = userPermissionHandler;
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public List<PermissionInfo> findUserPermissions(UserInfoDetails userInfoDetails) {
        String key = String.format(RedisKeyConstant.REDIS_KEY_USER_PERMISSIONS, userInfoDetails.getRoleId());
        String s = stringRedisTemplate.opsForValue().get(key);
        if (s == null || StringUtils.isBlank(s) || "[]".equals(s)) {
            List<PermissionInfo> permissions = userPermissionHandler.permissions(userInfoDetails);
            // 保存20分钟, 20分钟后自动删除
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(permissions), RedisKeyConstant.USER_PERMISSIONS_TIME_OUT, TimeUnit.MINUTES);
            return permissions;
        }
        return JSON.parseArray(s, PermissionInfo.class);
    }

}
